<template>
  <div class="smart-recommend">
    <!-- 推荐卡片 -->
    <transition-group name="recommend-list" tag="div" class="recommend-container">
      <el-card
        v-for="item in recommendations"
        :key="item.id"
        class="recommend-card"
        shadow="hover"
        @click="handleRecommendClick(item)"
      >
        <div class="recommend-header">
          <div class="recommend-icon" :style="{ background: item.color }">
            <el-icon :size="24">
              <component :is="item.icon" />
            </el-icon>
          </div>
          <div class="recommend-info">
            <div class="recommend-title">{{ item.title }}</div>
            <div class="recommend-desc">{{ item.description }}</div>
          </div>
          <el-tag :type="item.tagType" size="small">{{ item.tag }}</el-tag>
        </div>
        
        <div class="recommend-meta">
          <div class="meta-item">
            <el-icon><Star /></el-icon>
            <span>{{ item.score }}</span>
          </div>
          <div class="meta-item">
            <el-icon><View /></el-icon>
            <span>{{ item.views }}</span>
          </div>
          <div class="meta-item">
            <el-icon><Clock /></el-icon>
            <span>{{ item.updateTime }}</span>
          </div>
        </div>
        
        <div class="recommend-reason">
          <el-icon><InfoFilled /></el-icon>
          <span>{{ item.reason }}</span>
        </div>
        
        <div class="recommend-actions">
          <el-button size="small" type="primary" @click.stop="useRecommend(item)">
            立即使用
          </el-button>
          <el-button size="small" @click.stop="previewRecommend(item)">
            预览
          </el-button>
          <el-button
            size="small"
            :icon="item.isFavorite ? 'StarFilled' : 'Star'"
            @click.stop="toggleFavorite(item)"
          />
        </div>
      </el-card>
    </transition-group>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button :loading="loading" @click="loadMore">
        加载更多推荐
      </el-button>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      :title="currentItem?.title"
      width="80%"
      top="5vh"
    >
      <div v-if="currentItem" class="preview-content">
        <el-tabs v-model="previewTab">
          <el-tab-pane label="预览" name="preview">
            <div class="preview-area">
              <!-- 这里显示预览内容 -->
              <el-empty description="预览功能开发中..." />
            </div>
          </el-tab-pane>
          <el-tab-pane label="详情" name="detail">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="名称">{{ currentItem.title }}</el-descriptions-item>
              <el-descriptions-item label="类型">{{ currentItem.type }}</el-descriptions-item>
              <el-descriptions-item label="评分">{{ currentItem.score }}</el-descriptions-item>
              <el-descriptions-item label="浏览量">{{ currentItem.views }}</el-descriptions-item>
              <el-descriptions-item label="更新时间" :span="2">
                {{ currentItem.updateTime }}
              </el-descriptions-item>
              <el-descriptions-item label="描述" :span="2">
                {{ currentItem.description }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="使用说明" name="usage">
            <div class="usage-content">
              <h3>使用步骤：</h3>
              <ol>
                <li>点击"立即使用"按钮</li>
                <li>根据提示进行配置</li>
                <li>预览效果并调整</li>
                <li>保存并发布</li>
              </ol>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-button type="primary" @click="useCurrentItem">立即使用</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Star,
  StarFilled,
  View,
  Clock,
  InfoFilled,
  Document,
  Grid,
  Edit,
  Connection,
  Cpu,
  ShoppingBag
} from '@element-plus/icons-vue'

const props = defineProps({
  context: {
    type: String,
    default: 'general' // general, form, page, api, etc.
  },
  userBehavior: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['select', 'use'])

const recommendations = ref([])
const loading = ref(false)
const hasMore = ref(true)
const previewVisible = ref(false)
const currentItem = ref(null)
const previewTab = ref('preview')
const favoriteIds = ref(new Set())

// 推荐算法：基于用户行为和上下文
const generateRecommendations = () => {
  const baseRecommends = [
    {
      id: 'rec-1',
      type: 'template',
      title: 'CRUD表格模板',
      description: '完整的增删改查表格页面，支持搜索、分页、导出等功能',
      icon: 'Grid',
      color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      tag: '热门',
      tagType: 'danger',
      score: 4.9,
      views: 1580,
      updateTime: '2天前',
      reason: '基于您最近的浏览记录推荐',
      weight: 10
    },
    {
      id: 'rec-2',
      type: 'component',
      title: '高级表单组件',
      description: '支持动态字段、联动验证、分步表单的高级表单组件',
      icon: 'Edit',
      color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
      tag: '推荐',
      tagType: 'success',
      score: 4.8,
      views: 1230,
      updateTime: '3天前',
      reason: '与您正在开发的功能相似',
      weight: 9
    },
    {
      id: 'rec-3',
      type: 'template',
      title: '数据看板模板',
      description: '包含多种图表的数据可视化看板模板',
      icon: 'Document',
      color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
      tag: '新品',
      tagType: 'warning',
      score: 4.7,
      views: 980,
      updateTime: '1周前',
      reason: '同类项目经常使用',
      weight: 8
    },
    {
      id: 'rec-4',
      type: 'api',
      title: 'RESTful API模板',
      description: '标准的RESTful API接口设计模板',
      icon: 'Connection',
      color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
      tag: '实用',
      tagType: 'info',
      score: 4.6,
      views: 850,
      updateTime: '5天前',
      reason: '基于您的技术栈推荐',
      weight: 7
    },
    {
      id: 'rec-5',
      type: 'component',
      title: '智能搜索组件',
      description: '支持多条件筛选、历史记录、智能提示的搜索组件',
      icon: 'Cpu',
      color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
      tag: 'AI',
      tagType: 'success',
      score: 4.8,
      views: 1150,
      updateTime: '4天前',
      reason: '使用AI技术，提升用户体验',
      weight: 9
    },
    {
      id: 'rec-6',
      type: 'template',
      title: '审批流程模板',
      description: '完整的审批流程页面，支持多级审批、条件分支',
      icon: 'ShoppingBag',
      color: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
      tag: '热门',
      tagType: 'danger',
      score: 4.7,
      views: 1320,
      updateTime: '1天前',
      reason: '您的团队成员正在使用',
      weight: 8
    }
  ]

  // 根据上下文过滤
  let filtered = baseRecommends
  
  if (props.context !== 'general') {
    filtered = baseRecommends.filter(item => {
      if (props.context === 'form') return item.type === 'component' || item.title.includes('表单')
      if (props.context === 'page') return item.type === 'template'
      if (props.context === 'api') return item.type === 'api'
      return true
    })
  }

  // 根据用户行为调整权重
  if (props.userBehavior.recentViews) {
    filtered.forEach(item => {
      if (props.userBehavior.recentViews.includes(item.type)) {
        item.weight += 2
      }
    })
  }

  // 按权重排序
  filtered.sort((a, b) => b.weight - a.weight)

  // 检查收藏状态
  filtered.forEach(item => {
    item.isFavorite = favoriteIds.value.has(item.id)
  })

  return filtered
}

// 加载推荐
const loadRecommendations = () => {
  loading.value = true
  
  setTimeout(() => {
    const newRecommends = generateRecommendations()
    recommendations.value = [...recommendations.value, ...newRecommends]
    loading.value = false
    hasMore.value = false // 演示用，实际应根据数据判断
  }, 500)
}

// 加载更多
const loadMore = () => {
  loadRecommendations()
}

// 点击推荐项
const handleRecommendClick = (item) => {
  emit('select', item)
  
  // 记录点击行为
  recordBehavior('click', item)
}

// 使用推荐
const useRecommend = (item) => {
  emit('use', item)
  ElMessage.success(`正在应用"${item.title}"...`)
  
  // 记录使用行为
  recordBehavior('use', item)
}

// 预览推荐
const previewRecommend = (item) => {
  currentItem.value = item
  previewVisible.value = true
  previewTab.value = 'preview'
  
  // 记录预览行为
  recordBehavior('preview', item)
}

// 使用当前项
const useCurrentItem = () => {
  if (currentItem.value) {
    useRecommend(currentItem.value)
    previewVisible.value = false
  }
}

// 切换收藏
const toggleFavorite = (item) => {
  if (favoriteIds.value.has(item.id)) {
    favoriteIds.value.delete(item.id)
    item.isFavorite = false
    ElMessage.success('已取消收藏')
  } else {
    favoriteIds.value.add(item.id)
    item.isFavorite = true
    ElMessage.success('已添加收藏')
  }
  
  // 保存收藏状态
  saveFavorites()
}

// 记录用户行为
const recordBehavior = (action, item) => {
  const behavior = {
    action,
    itemId: item.id,
    itemType: item.type,
    timestamp: new Date().getTime()
  }
  
  // 保存到本地存储
  const behaviors = JSON.parse(localStorage.getItem('recommend_behaviors') || '[]')
  behaviors.push(behavior)
  
  // 最多保留1000条
  if (behaviors.length > 1000) {
    behaviors.shift()
  }
  
  localStorage.setItem('recommend_behaviors', JSON.stringify(behaviors))
}

// 保存收藏
const saveFavorites = () => {
  localStorage.setItem('recommend_favorites', JSON.stringify([...favoriteIds.value]))
}

// 加载收藏
const loadFavorites = () => {
  const saved = localStorage.getItem('recommend_favorites')
  if (saved) {
    try {
      favoriteIds.value = new Set(JSON.parse(saved))
    } catch (e) {
      console.error('Failed to load favorites:', e)
    }
  }
}

// 监听上下文变化
watch(() => props.context, () => {
  recommendations.value = []
  hasMore.value = true
  loadRecommendations()
})

onMounted(() => {
  loadFavorites()
  loadRecommendations()
})
</script>

<style scoped>
.smart-recommend {
  padding: 20px 0;
}

.recommend-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.recommend-card {
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 2px solid transparent;
}

.recommend-card:hover {
  transform: translateY(-4px);
  border-color: #409eff;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.2);
}

.recommend-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.recommend-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.recommend-info {
  flex: 1;
  min-width: 0;
}

.recommend-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.recommend-desc {
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.recommend-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 12px;
  padding: 12px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #909399;
}

.meta-item .el-icon {
  color: #c0c4cc;
}

.recommend-reason {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  background: #ecf5ff;
  border-radius: 6px;
  font-size: 13px;
  color: #409eff;
  margin-bottom: 16px;
}

.recommend-actions {
  display: flex;
  gap: 8px;
}

.recommend-actions .el-button {
  flex: 1;
}

.load-more {
  text-align: center;
  padding: 20px 0;
}

/* 预览内容 */
.preview-content {
  min-height: 400px;
}

.preview-area {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  min-height: 400px;
}

.usage-content {
  padding: 20px;
}

.usage-content h3 {
  margin-bottom: 16px;
  color: #303133;
}

.usage-content ol {
  padding-left: 24px;
}

.usage-content li {
  margin-bottom: 12px;
  color: #606266;
  line-height: 1.6;
}

/* 列表动画 */
.recommend-list-enter-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.recommend-list-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.recommend-list-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.recommend-list-leave-to {
  opacity: 0;
  transform: scale(0.9);
}

.recommend-list-move {
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 响应式 */
@media (max-width: 768px) {
  .recommend-container {
    grid-template-columns: 1fr;
  }
}
</style>

